import Reflux from 'reflux';
import Actions from "./Actions";
import {ListView, Modal, Toast} from "antd-mobile";
import update from 'react-addons-update';
import DB from '../../../../app/db';
import StorageUtils from "../../../../app/storage";
import {Control} from "react-keeper";
import Utils from "../../../../utils/index";
const ModalAlert = Modal.alert;

function formatData(data) {
  return {
    img: '',
    // 投票名称
    title: data.name,
    // 投票ID
    voteId: data.id,
    // 投票状态
    active: data.planState === 3,
    // 投票描述
    des: data.title,
    // 投票规则说明
    roleIntroduce: data.role,
    startTime: data.planStartTime,
    endTime: data.planEndTime,
    // 方案详细说明
    planIntroduce: data.description,
    // 方案图片
    imgaes: [],
    // 已投票数
    voteCount: data.planCount
  }
}

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    dataBlob: [],
    // activeDataBlob: [],
    // inactiveDataBlob: [],
    dataSourceActive: new ListView.DataSource({
      getRowData: (dataBlob, rowID) => dataBlob[rowID],
      rowHasChanged: (row1, row2) => row1 !== row2,
    }),
    dataSourceInactive: new ListView.DataSource({
      getRowData: (dataBlob, rowID) => dataBlob[rowID],
      rowHasChanged: (row1, row2) => row1 !== row2,
    }),
    isLoading: false,
    hasMore: true,
    pageSize: 10,
    currentPage: 1,
    isError: false,
    currentTab: 0,
    userInfo: {}
  },

  init() {
    this.data.userInfo = update(this.data.userInfo, {$set: StorageUtils.getUser()});
    // 获取投票列表
    this.data.dataBlob = [];
    this.initDataSource();
    this.updateComponent();
  },

  // 投票列表初始化（active: boolean 已结束/进行中）
  initVoteList() {

    let t = this;
    let param = {
      proprietorId: t.data.userInfo.proprietorId,
      planState: t.data.currentTab === 0 ? '3' : '4'
    };
    DB.WechatAPI.getVoteListByProprietorId(param).then(
      function (content) {
        let dataBlob = [];
        if (content && content.length > 0) {
          content.map(data => dataBlob.push(formatData(data)));
        }
        t.data.dataBlob = dataBlob;
        t.updateDataSource(t.data.currentTab === 0);
        t.updateComponent();
      },
      function (error) {
        console.log(error);
        Toast.fail('获取数据失败，请退出或刷新重试。', 1);
        t.data.dataBlob = [];
        t.updateDataSource();
        t.updateComponent();
      }
    );
  },

  initDataSource() {
    this.data = update(this.data, {
      dataSourceActive: {$set: this.data.dataSourceActive.cloneWithRows([])},
      dataSourceInactive: {$set: this.data.dataSourceInactive.cloneWithRows([])},
      isLoading: {$set: false}
    });
  },

  updateDataSource(active) {
    if (active) {
      let dataSourceActive = this.data.dataSourceActive.cloneWithRows(this.data.dataBlob);
      this.data = update(this.data, {
        dataSourceActive: {$set: dataSourceActive},
        isLoading: {$set: false}
      });
    } else {
      let dataSourceInactive = this.data.dataSourceInactive.cloneWithRows(this.data.dataBlob);
      this.data = update(this.data, {
        dataSourceInactive: {$set: dataSourceInactive},
        isLoading: {$set: false}
      });
    }
  },

  onEndReached(active) {

    console.log('onEndReached', active);
    this.startReloadVoteList();

    // this.data.dataBlob = update(this.data.dataBlob, {$push: []});

    if (active) {
      setTimeout(() => {
        let dataSourceActive = this.data.dataSourceActive.cloneWithRows(this.filterDataBlob(active));
        this.data = update(this.data, {
          dataSourceActive: {$set: dataSourceActive},
          isLoading: {$set: false}
        });
        this.updateComponent();
      }, 1000);
    } else {
      setTimeout(() => {
        let dataSourceInactive = this.data.dataSourceInactive.cloneWithRows(this.filterDataBlob(active));
        this.data = update(this.data, {
          dataSourceInactive: {$set: dataSourceInactive},
          isLoading: {$set: false}
        });
        this.updateComponent();
      }, 1000);
    }
  },

  onTabChange(active) {
    let t = this;
    t.data = update(t.data, {
      currentTab: {$set: active ? 0 : 1}
    });
    t.updateComponent();
    // this.clearVoteList();
    t.startReloadVoteList();

    t.initVoteList();
  },

  onTabClick(active) {

    // this.clearVoteList();
    this.startReloadVoteList();
    if (active) {
      setTimeout(() => {
        let dataSourceActive = this.data.dataSourceActive.cloneWithRows(this.filterDataBlob(active));
        this.data = update(this.data, {
          dataSourceActive: {$set: dataSourceActive},
          isLoading: {$set: false},
          currentTab: {$set: active ? 0 : 1}
        });
        this.updateComponent();
      }, 1000);
    } else {
      setTimeout(() => {
        let dataSourceInactive = this.data.dataSourceInactive.cloneWithRows(this.filterDataBlob(active));
        this.data = update(this.data, {
          dataSourceInactive: {$set: dataSourceInactive},
          isLoading: {$set: false},
          currentTab: {$set: active ? 0 : 1}
        });
        this.updateComponent();
      }, 1000);
    }
  },

  startReloadVoteList() {
    if (this.data.isLoading && !this.data.hasMore) {
      return;
    }

    this.data.isLoading = true;
    this.updateComponent();
  },

  clearVoteList(active) {
    if (active) {
      let dataSourceActive = this.data.dataSourceActive.cloneWithRows([]);
      this.data.dataSourceActive = update(this.data.dataSourceActive, {
        dataSourceActive: {$set: dataSourceActive},
      });
    } else {
      let dataSourceInactive = this.data.dataSourceInactive.cloneWithRows([]);
      this.data.dataSourceInactive = update(this.data.dataSourceInactive, {
        dataSourceInactive: {$set: dataSourceInactive},
      });
    }
    this.updateComponent();
  },

  filterDataBlob(active) {
    return this.data.dataBlob.filter(obj => obj.active === active);
  },

  showAlert(){
    const alertInstance = ModalAlert('您还没有绑定账号', '是否现在去绑定?', [
      { text: '取消', onPress: () => console.log('cancel')},
      { text: '绑定', onPress: () => {Control.go('/home/user/register', null)}, style: 'default' },
    ]);
    setTimeout(() => {
      // 可以调用close方法以在外部close
      console.log('auto close');
      alertInstance.close();
    }, 5000);

    // Toast.info('您还未绑定用户，无法进行投票。', 3);
  },

updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState() {
    return this.data;
  }
});
